package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkSpaceService workSpaceService;

    /**
     * 统计指定时间内的区间的营业额
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnOverStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end每天的日期
        List<LocalDate> localDates = getLocalDates(begin, end);

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        String dateList = StringUtils.join(localDates, ",");
        turnoverReportVO.setDateList(dateList);
        List<Double> turnOverList = new ArrayList<>();
        for (LocalDate date : localDates) {
            //查询date日期对应营业额数据 ：状态为已完成的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnOverList.add(turnover);
            //select sum(amount) from orders where order_time>?  and order_time<?  and status=?
        }
        String turnoverList = StringUtils.join(turnOverList, ",");
        turnoverReportVO.setTurnoverList(turnoverList);
        return turnoverReportVO;
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //1、计算出时间集合
        List<LocalDate> dateList = getLocalDates(begin, end);
        String DateList = StringUtils.join(dateList, ",");
        List<Long> newUserList = new ArrayList<>();
        List<Long> totalUserList = new ArrayList<>();
        //查表得出新增用户
        //每一天的新增用户
        //查询每一天的总用户
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map newUserMap = new HashMap();
            Map totalUserMap = new HashMap();
            newUserMap.put("begin", beginTime);
            newUserMap.put("end", endTime);
            totalUserMap.put("end", endTime);
            Long newUserNumber = orderMapper.UserSumByMap(newUserMap);
            Long totalUserNumber = orderMapper.UserSumByMap(totalUserMap);
            totalUserList.add(totalUserNumber);
            newUserList.add(newUserNumber);
        }

        String NewUserList = StringUtils.join(newUserList, ",");
        String TotalUserList = StringUtils.join(totalUserList, ",");

        return UserReportVO.builder()
                .dateList(DateList)
                .newUserList(NewUserList)
                .totalUserList(TotalUserList)
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //dateList
        List<LocalDate> localDates = getLocalDates(begin, end);
        String dateList = StringUtils.join(localDates, ",");


        //订单总数
        Integer totalOrderCount = orderMapper.selectAll().size();
        //有效订单数:已完成
        Integer validOrderCount = orderMapper.selectValidOrder(Orders.COMPLETED);
        //orderCompletionRate 订单完成率
        //订单完成数量/总订单数量
        Double orderCompletionRate = validOrderCount * (1.00) / totalOrderCount;
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate localDate : localDates) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map OrderCountMap = new HashMap();
            Map validOrderCountMap = new HashMap();
            OrderCountMap.put("begin", beginTime);
            OrderCountMap.put("end", endTime);
            validOrderCountMap.put("begin", beginTime);
            validOrderCountMap.put("end", endTime);
            validOrderCountMap.put("status", Orders.COMPLETED);
            Integer orderCount = orderMapper.CountByMap(OrderCountMap);
            Integer validOrderCountForList = orderMapper.CountByMap(validOrderCountMap);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCountForList);
        }

        return OrderReportVO.builder()
                .dateList(dateList)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .build();
    }

    /**
     * 查询销量排名top10接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //得到前十的菜品
        List<GoodsSalesDTO> goodsSalesDTOList = orderDetailMapper.getTop10(beginTime, endTime);
        List<Integer> number_list = new ArrayList<>();
        List<String> name_list = new ArrayList<>();
        //可以用stream流来解决。代码更加简洁
        //List<String> names = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());

        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {
            String name = goodsSalesDTO.getName();
            Integer number = goodsSalesDTO.getNumber();
            number_list.add(number);
            name_list.add(name);
        }

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(name_list, ","))
                .numberList(StringUtils.join(number_list, ","))
                .build();


    }

    /**
     * 导出运行数据报表
     *
     * @param response
     */
    @Override
    public void exportBuisnessDate(HttpServletResponse response) {
        //1、查询数据库获取营业数据----最近30天
        //查询概览数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);
        BusinessDataVO businessDataVO = workSpaceService.businessData(begin, end);
        //2、通过poi写入到excel文件当中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/dateTemplate.xlsx");
        //基于模板文件创建一个新的模板文件
        try {
            XSSFWorkbook excel = new XSSFWorkbook(is);
            //获取表格文件的标签页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);
            //获得第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //获得第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                BusinessDataVO businessData = workSpaceService.businessData(LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));
                //获得某一行
                row = sheet.getRow(i + 7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());


            }


            //3、通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 得到时间列表
     *
     * @param begin
     * @param end
     * @return
     */
    private static List<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = new ArrayList<>();
        localDates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDates.add(begin);
        }
        return localDates;
    }
}
